import { _decorator, Component, EventMouse, EventTouch, math, Node, Sprite, Vec2, Vec3 } from "cc";
import { Vec2Util } from "../com/util/Vec2Util";
const { ccclass, property } = _decorator;

/**
 * 摇杆
 */
@ccclass('Rocker')
export class Rocker extends Component {
    @property(Sprite)
    bg: Sprite;
    @property(Sprite)
    small: Sprite;
    /**中心移动最大距离 */
    private maxDis: number = 35;
    /**摇杆中心点当前x(世界坐标) */
    public x: number;
    /**摇杆中心当前y(世界坐标) */
    public y: number;
    /**摇杆中心点位置(世界坐标) */
    public midPos: Vec3;
    /**摇杆当前角度,0-360，传出去的 */
    public angle:number;
    start() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouch, this);
        this.midPos = this.small.node.getWorldPosition();
    }

    update(deltaTime: number) {

    }

    onTouch(e: EventTouch): void {
        this.setPos(e);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    onTouchMove(e: EventTouch): void {
        this.setPos(e);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onTouchEnd(e: EventTouch): void {
        this.angle = 0;
        this.small.node.position = new Vec3(0, 0, 0);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchMove, this);
    }

    setPos(e: EventTouch): void {
        let touchPos: math.Vec2 = e.getLocation();
        let dis: number = Vec2Util.getDis(touchPos, this.midPos);
        dis = dis > this.maxDis ? this.maxDis : dis;
        //角度
        this.angle = Vec2Util.getAngle(this.midPos.x, this.midPos.y, touchPos.x, touchPos.y);
        //弧度
        let radian = math.toRadian(this.angle);

        this.x = dis * Math.cos(radian);

        this.y = dis * Math.sin(radian);

        this.small.node.position = new math.Vec3(this.x, this.y, 0);
    }

    /**获取摇杆当前弧度 */
    public get radian():number{
        return math.toRadian(this.angle);
    }

    

    

    
}

